﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Zhang.Utils
{
    public class DecimalHelper
    {
        /// <summary>
        /// Decimal类型截取保留N位小数并且不进行四舍五入操作
        /// </summary>
        /// <param name="d"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static decimal CutDecimalWithN(decimal d, int n)
        {
            string strDecimal = d.ToString();
            int index = strDecimal.IndexOf(".");
            if (index == -1 || strDecimal.Length < index + n + 1)
            {
                strDecimal = string.Format("{0:F" + n + "}", d);
            }
            else
            {
                int length = index;
                if (n != 0)
                {
                    length = index + n + 1;
                }
                strDecimal = strDecimal.Substring(0, length);
            }
            return Decimal.Parse(strDecimal);
        }

        /// <summary>
        ///  Decimal类型截取保留N位小数向上取
        /// </summary>
        /// <param name="d"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        public static decimal Ceiling(decimal d, int n)
        {
            decimal t = decimal.Parse(Math.Pow(10, n).ToString());
            d = Math.Ceiling(t * d);
            return d / t;
        }
    }
}
